package com.lx.util.secure.algorithm.encrypt;


import com.lx.util.secure.algorithm.SecureAlgorithm;
import com.lx.util.secure.algorithm.coder.CoderType;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Arrays;
import java.util.List;


public class Aes extends SecureAlgorithm<Aes> {

    private static final String KEY_ALGORITHM = "AES";
    private static final List<Integer> KEY_CHAR_ARRAY = Arrays.asList(16, 24, 32);

    @Override
    protected CoderType defaultKeyCoderType() {
        return CoderType.DEFAULT;
    }

    @Override
    protected CoderType defaultCoderType() {
        return CoderType.BASE64;
    }

    @Override
    protected String defaultEncryptAlgorithm() {
        return "AES/CBC/PKCS7Padding";
    }

    @Override
    public Aes key(String keyStr) {
        // aes算法的秘钥要求是16位、24位、32位
        if (!KEY_CHAR_ARRAY.contains(keyStr.length())) {
            throw new IllegalArgumentException("AES秘钥长度要求为16位、24位、32位");
        }
        return super.key(keyStr);
    }

    @Override
    public byte[] encrypt(byte[] bytes) {
        try {
            Cipher cipher = Cipher.getInstance(getEncryptAlgorithm());
            Key sKeySpec = new SecretKeySpec(getKey(), KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, new IvParameterSpec(getIv()));
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public byte[] decrypt(byte[] bytes) {
        try{
            Cipher cipher = Cipher.getInstance(getEncryptAlgorithm());
            Key sKeySpec = new SecretKeySpec(getKey(), KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, new IvParameterSpec(getIv()));
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
